# coding: utf-8

import sys
import os
import hmac
import hashlib
import time
kilobytes = 1024
megabytes = kilobytes*1000
chunksize = int(200*megabytes)  # default chunksize
sha256_key = '123456'
# 切割文件
reload(sys)
sys.setdefaultencoding('utf-8')


def split(fromfile, todir, chunksize=chunksize):
    if not os.path.exists(todir):  # check whether todir exists or not
        os.mkdir(todir)
    else:
        for fname in os.listdir(todir):
            os.remove(os.path.join(todir, fname))
    partnum = 0
    inputfile = open(fromfile, 'rb')  # open the fromfile
    while True:
        chunk = inputfile.read(chunksize)
        if not chunk:  # check the chunk is empty
            break
        partnum += 1
        filename = os.path.join(todir, ('%08d' % partnum))
        fileobj = open(filename, 'wb')  # make partfile
        fileobj.write(chunk)  # write data into partfile
        fileobj.close()
    return partnum


def file_sha256(filepath):
    '''
    sha256加密
    return:加密结果转成16进制字符串形式，并大写
    '''
    infile = open(filepath, 'rb')
    data = infile.read()
    hsobj = hashlib.sha256(data)
    infile.close()
    return hsobj.hexdigest().upper()


def merge(path, data, i):
    print (path)
    with open(path, "r+") as f:
        old = f.read()
        f.seek(0)
        f.write(data)
        f.write(old)
        f.close()


def eightIntStr(value):
    str1 = "00000000"+str(value)
    return str1[-8:]


def join(file_name, id, content):
    '''sha256内容+size+id+源文件内容'''
    size = os.path.getsize(file_name)


def dealData():
    todir = '/Users/forke/Documents/project/_project/python/cutFile/out'
    i = 0
    for fname in os.listdir(todir):
        filename = os.path.join(todir, fname)
        # 加密
        str_256 = file_sha256(filename)
        #print (str_256)
        # 源文件大小
        size = os.path.getsize(filename)
        size = eightIntStr(size)
        content = str_256+str(size)+str(eightIntStr(fname))
        # 重新写入加密文件
        merge(filename, content, i)
        #print (i)
        i = i+1


if __name__ == '__main__':
    start = time.clock()

    fromfile = '/Users/forke/Documents/project/_project/python/cutFile/66671.txt'
    todir = '/Users/forke/Documents/project/_project/python/cutFile/out'
    chunksize = 2*1024*1000
    absfrom, absto = map(os.path.abspath, [fromfile, todir])
    print('Splitting', absfrom, 'to', absto, 'by', chunksize)
    try:
        parts = split(fromfile, todir, chunksize)
        # dealData()
    except:
        print('Error during split:')
        print(sys.exc_info()[0], sys.exc_info()[1])
    else:
        print('split finished:', parts, 'parts are in', absto)
        dealData()
        elapsed = (time.clock() - start)
        print("Time used:", elapsed)
